    //
//  QueryFlightViewController.m
//  AirTicket
//
//  Created by imac.bmw on 10-12-21.
//  Copyright 2010 aircococ. All rights reserved.
//

#import "QueryFlightViewController.h"
#import "QueryFlightCell.h"
#import "CityListViewController.h"
#import <QuartzCore/QuartzCore.h>


@implementation QueryFlightViewController
@synthesize table;
@synthesize cityController;
@synthesize flightInfo;
@synthesize queryAction;
@synthesize showTicket;
@synthesize waiting;
@synthesize waitingView;
@synthesize org;
@synthesize dest;
@synthesize date;
@synthesize activity;
@synthesize airwayCode;
// Implement loadView to create a view hierarchy programmatically
- (void)loadView {
	[super loadView];
	
	//NSMutableDictionary * aFlightInfo = [[NSMutableDictionary alloc]initWithCapacity:100];
//	self.flightinfo = aFlightInfo;
//	
//	[aFlightInfo release];
	QueryFlight *queryFlight = [[QueryFlight alloc]init];
	self.queryAction = queryFlight;
	[queryFlight release];
	queryAction.delegate = self;
	
	//初始化table
	UITableView *aTable = [[UITableView alloc]initWithFrame:CGRectMake(10, 2, 300, 280) style:UITableViewStylePlain];
	self.table = aTable;
	self.table.scrollEnabled = NO;
	self.table.dataSource = self;
	self.table.delegate = self;
	//self.table.backgroundColor = [UIColor clearColor];
	[aTable release];
	
//	UIScrollView *content = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 380)];
//	content.contentSize = CGSizeMake(320, 480);
//	content.showsVerticalScrollIndicator = NO;
	[self.view addSubview:self.table];
//	[self.view addSubview:content];
	

	
	UIImage *chaxun = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"query" ofType:@"png"]];
	queryButton = [[UIButton alloc]initWithFrame:CGRectMake(34, 300, chaxun.size.width, chaxun.size.height)];
	[queryButton setBackgroundImage:chaxun forState:UIControlStateNormal];
	[self.view addSubview:queryButton];
	[queryButton addTarget:self action:@selector(goQuery) forControlEvents:UIControlEventTouchUpInside];
	[queryButton release];
	
	//添加head view
	UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 35)];
	//header.backgroundColor = [UIColor blueColor];
	table.tableHeaderView = header;
	[header release];
	
	flightKind = [[UISegmentedControl alloc]initWithItems:nil];
	flightKind.frame = CGRectMake(50, 0, 200, 30);
	flightKind.segmentedControlStyle = UISegmentedControlStylePlain;
	flightKind.tintColor = [UIColor colorWithRed:0.75 green:1.0 blue:0.75 alpha:1.0];
	[flightKind insertSegmentWithTitle:@"单程" atIndex:0 animated:NO];
	[flightKind insertSegmentWithTitle:@"往返" atIndex:1 animated:NO];
	flightKind.selectedSegmentIndex = 0;
	[flightKind addTarget:self action:@selector(selectFlightKind) forControlEvents:UIControlEventValueChanged];
	[table.tableHeaderView addSubview:flightKind];
	[flightKind release];
	
	
	
}

//点击查询按妞，进入查询状态
-(void)goQuery {

	queryButton.enabled = NO;
	
	if (flightKind.selectedSegmentIndex == 0) {
		[SaveDefaults setObject:@"单程" forKey:@"singleOrDouble"];
		//[SaveDefaults setObject:@"0" forKey:@"queryAgain"];
	}
	else {
		[SaveDefaults setObject:@"往返" forKey:@"singleOrDouble"];
		//[SaveDefaults setObject:@"去程" forKey:@"title"];
	}

	queryAction.flightDate = [SaveDefaults objectForKey:@"goDate"];
	queryAction.airway = [SaveDefaults objectForKey:@"airwayCode"];
	
	if (flightKind.selectedSegmentIndex == 0) {
	if (queryAction.orig==nil || queryAction.dest==nil || queryAction.flightDate==nil || queryAction.airway==nil) {
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"出错了" message:@"缺少必要信息" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
	
		[alert show];
		[alert release];
	}
		else {
			[queryAction getTicketInfo];
			[self addWaitingView];
		}

	}
	else {
		
		NSString *backDate = [SaveDefaults valueForKey:@"backDate"];
		if (!queryAction.orig || !queryAction.dest || !queryAction.flightDate || !backDate || !queryAction.airway) {
			UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"出错了" message:@"缺少必要信息" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
			
			[alert show];
			[alert release];
		}
		else {
			[queryAction getTicketInfo];
			[self addWaitingView];
		}
	}
	
}

//加入查询时等待的提示框
-(void)addWaitingView {

	UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 60, 100, 20)];
	self.waiting = label;
	[label release];
	waiting.backgroundColor = [UIColor clearColor];
	waiting.text = @"正在查询...";
	waiting.textColor = [UIColor whiteColor];
	
	UIView * theWaitingView = [[UIView alloc]initWithFrame:CGRectMake(110, 150, 110, 90)];
	self.waitingView = theWaitingView;
	[theWaitingView release];
	waitingView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.77];
	waitingView.alpha = 0.8f;
	waitingView.layer.masksToBounds = YES;
	waitingView.layer.cornerRadius = 7;
	
	UIActivityIndicatorView * m_activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
	self.activity = m_activity;
	[m_activity release];
	activity.frame = CGRectMake(45, 35, 20, 20);
	[waitingView addSubview:activity];
	[activity startAnimating];
	[waitingView addSubview:waiting];
	[self.view addSubview:waitingView];
	
}

//查询到结果后显示结果
-(void)didGetResluts:(QueryResults *)result {
	queryButton.enabled = YES;
	[activity stopAnimating];
	[waitingView removeFromSuperview];
	
	showTicket = [[ShowTicketsViewController alloc]init];
	
	QueryResults *aResult = [result retain];
	//NSUserDefaults *info = [];
	showTicket.Result = aResult;
	showTicket.date = [SaveDefaults objectForKey:@"goDate"];
	showTicket.org = [SaveDefaults valueForKey:@"org"];
	showTicket.dest = [SaveDefaults valueForKey:@"dst"];
	showTicket.airwayCode = [SaveDefaults objectForKey:@"airwayCode"];
	showTicket.navTitle = @"选择去程航班";
	[self.navigationController pushViewController:showTicket animated:YES];

	[aResult release];
	[showTicket release];
}

-(void)selectFlightKind {

	if (flightKind.selectedSegmentIndex == 0) {
		self.table.frame = CGRectMake(10, 2, 300, 280);
	}
	else {
		self.table.frame = CGRectMake(10, 2, 300, 340);
	}
	
	[self.table reloadData];
	
	UIImage *chaxun = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"query" ofType:@"png"]];

	int height = self.table.frame.size.height;
	queryButton.frame = CGRectMake(34, height+20, chaxun.size.width, chaxun.size.height);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	if (flightKind.selectedSegmentIndex == 0) {
		return 4;
	}
	else
	return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	
		return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	NSInteger row = [indexPath row];
	if (flightKind.selectedSegmentIndex == 0) {
		static NSString *CellIdentifier = @"fourRow";
		
		QueryFlightCell *cell = (QueryFlightCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) 
		{
			cell = [[[QueryFlightCell alloc] initWithFrame:CGRectMake(0, 0, 300.0, 60.0) reuseIdentifier:CellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}
		
		if (row == 0) {
			cell.nameLabel.text = @"出发城市";
			cell.picView.image = [UIImage imageNamed:@"org.png"];
		}
		else if (row == 1){
			cell.nameLabel.text = @"目的城市";
		cell.picView.image = [UIImage imageNamed:@"dst.png"];
		}
		else if (row == 2) {
			cell.nameLabel.text = @"出发日期";
		cell.picView.image = [UIImage imageNamed:@"date.png"];
			
			NSDate *today = [NSDate date];
			NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
			[outputFormat setDateFormat:@"yyyy-MM-dd"];
			NSString *myNewDateString = [outputFormat stringFromDate:today];
			cell.paraLabel.text = myNewDateString;
			[SaveDefaults setObject:myNewDateString forKey:@"goDate"];
			[outputFormat release];
		}
		else if (row == 3){
			cell.nameLabel.text = @"航空公司";	
		cell.picView.image = [UIImage imageNamed:@"airway.png"];
			cell.paraLabel.text = @"全部";
			[SaveDefaults setObject:@"ALL" forKey:@"airwayCode"];
		}
		return cell;
	}
	
	else  if (flightKind.selectedSegmentIndex == 1) {
		static NSString *CellIdentifier = @"fiveRow";
		
		QueryFlightCell *cell = (QueryFlightCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) 
		{
			cell = [[[QueryFlightCell alloc] initWithFrame:CGRectMake(0, 0, 300.0, 60.0) reuseIdentifier:CellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}
		
		if (row == 0) {
			cell.nameLabel.text = @"出发城市";
			cell.picView.image = [UIImage imageNamed:@"org.png"];
		}
		else if (row == 1) {
			cell.nameLabel.text = @"目的城市";
		cell.picView.image = [UIImage imageNamed:@"dst.png"];
		}
		else if (row == 2) {
			cell.nameLabel.text = @"出发日期";
		cell.picView.image = [UIImage imageNamed:@"date.png"];
			
			NSDate *today = [NSDate date];
			NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
			[outputFormat setDateFormat:@"yyyy-MM-dd"];
			NSString *myNewDateString = [outputFormat stringFromDate:today];
			cell.paraLabel.text = myNewDateString;
			[SaveDefaults setObject:myNewDateString forKey:@"goDate"];
			[outputFormat release];
		}
		else if (row == 3){
			cell.nameLabel.text = @"返程日期";
		cell.picView.image = [UIImage imageNamed:@"date.png"];
			
			NSDate *today = [NSDate date];
			today = [[NSDate alloc] initWithTimeInterval:24*3600 sinceDate:today];
			NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
			[outputFormat setDateFormat:@"yyyy-MM-dd"];
			NSString *myNewDateString = [outputFormat stringFromDate:today];
			cell.paraLabel.text = myNewDateString;
			[SaveDefaults setObject:myNewDateString forKey:@"backDate"];
			[outputFormat release];
			[today release];
		}
		else if (row == 4){
			cell.nameLabel.text = @"航空公司";	
		cell.picView.image = [UIImage imageNamed:@"airway.png"];
			cell.paraLabel.text = @"全部";
			[SaveDefaults setObject:@"ALL" forKey:@"airwayCode"];
		}
		return cell;
	}
	else {
		static NSString *CellIdentifier = @"normal";
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) 
		{
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 300.0, 60.0) reuseIdentifier:CellIdentifier] autorelease];
		}
		
		return cell;
	}
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	int index = flightKind.selectedSegmentIndex;
	NSInteger row = indexPath.row;
	
		if (row == 0 || row == 1) {
			cityController = [[CityListViewController alloc]init];
			cityController.indexPathInTableView = indexPath;
			cityController.delegate = self;
			[self.navigationController pushViewController:cityController animated:YES];
			[cityController release];
		}
		else if ((row == 2 && index == 0) || (((row == 2 || row ==3)&&index == 1))){
			
			FlightDateViewController *dateController = [[FlightDateViewController alloc]init];
			dateController.delegate = self;
			dateController.indexPathInTableView = indexPath;
			[self.navigationController pushViewController:dateController animated:YES];
			[dateController release];
		}
		else if((row == 3 && index == 0) || (row == 4 && index == 1)) {
		
			AirwaysViewController *airController = [[AirwaysViewController alloc]init];
			airController.indexPathInTableView = indexPath;
			airController.delegate = self;
			[self.navigationController pushViewController:airController animated:YES];
			[airController release];
		}

	
	
}

//得到航空公司
- (void)didGetAirway:(NSString *)airway andCode:(NSString *)code atIndexPath:(NSIndexPath *)indexPath {

	QueryFlightCell *cell = (QueryFlightCell *)[self.table cellForRowAtIndexPath:indexPath];
	cell.paraLabel.text = airway;
	
	self.airwayCode = code;
	[SaveDefaults setObject:code forKey:@"airwayCode"];
}

- (void)didGetDate:(NSString *)flightDate atIndexPath:(NSIndexPath *)indexPath{
	
	QueryFlightCell *cell = (QueryFlightCell *)[self.table cellForRowAtIndexPath:indexPath];
	cell.paraLabel.text = flightDate;
	//self.date = flightDate;
	if (indexPath.row == 2) {
		
		self.date = flightDate;
		[SaveDefaults setObject:flightDate forKey:@"goDate"];
	}
	else if(indexPath.row == 3) {
	
		[SaveDefaults setObject:flightDate forKey:@"backDate"];
	}
								 
								 
}


- (void)didGetCity:(NSString *)cityName andCode:(NSString *)code atIndexPath:(NSIndexPath *)indexPath {

	QueryFlightCell *cell = (QueryFlightCell *)[self.table cellForRowAtIndexPath:indexPath];
	cell.paraLabel.text = cityName;
	
	if (indexPath.row == 0) {
		queryAction.orig = code;
		self.org = code;
		[SaveDefaults setValue:cityName forKey:@"org"];
		[SaveDefaults setValue:code forKey:@"orgcode"];
		
	}
	else {
		queryAction.dest = code;
		self.dest = code;
		[SaveDefaults setValue:cityName forKey:@"dst"];
		[SaveDefaults setValue:code forKey:@"dstcode"];
	}

}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[org release];
	[dest release];
	[date release];
	[airwayCode release];
	//[flightinfo release];
	[activity release];
	[waiting release];
	[waitingView release];
	[table release];
    [super dealloc];
}


@end
